//
//  CourseDetailsViewController.m
//  mUBB
//
//  Created by Cosmin Stirbu on 2/28/13.
//  Copyright (c) 2013 Cosmin Stirbu. All rights reserved.
//

#import "CourseDetailsViewController.h"
#import "NSString+Empty.h"
#import "UIViewAdditions.h"
#import "CoursesManager.h"
#import "WSError.h"
#import "Teacher.h"
#import "QuartzCore/QuartzCore.h"
#import "WebBrowserViewController.h"
#import "TeacherDetailsViewController.h"
#import "CourseBookingsViewController.h"
#import "Constants.h"
#import "NotificationsManager.h"


#define VERTICAL_SPACE (IS_IPAD() ? 40 : 20)

#define FACULTY_BUTTON_MINI_FONT_SIZE 13

#define ALERT_TAG_COURSE_DETAILS 1
#define ALERT_TAG_SUBSCRIBE 2
#define ALERT_TAG_UNSUBSCRIBE 3

@interface CourseDetailsViewController ()

@end

@implementation CourseDetailsViewController

@synthesize courseScheduleButton, courseWebsiteButton, facultyWebsiteButton, teachersTableView, headerLabel, scrollView, notificationsButton;

- (id)initWithNibName:(NSString *)nibNameOrNil course:(Course *)course
{
    self = [super initWithNibName:nibNameOrNil bundle:nil];
    if (self) {
        // Custom initialization
        _course = course;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = _course.courseName;
    // Get Course details
    [self getCourseDetails];
}

- (void)getCourseDetails {
    [Utils showLoadingOn:self];
    [[CoursesManager instance] getCourseDetailsForCourse:_course delegate:self];
}

- (void)setUpUI {
    // Set up the UI
    UIBarButtonItem *newBackButton = [[UIBarButtonItem alloc] initWithTitle: NSLocalizedString(@"BACK_BUTTON_NAVIGATION", nil) style: UIBarButtonItemStyleBordered target: nil action: nil];
    [[self navigationItem] setBackBarButtonItem: newBackButton];
    
    
    // Set up the UI
    courseScheduleButton.hidden = NO;
    [Utils customizeButton:courseScheduleButton withBgImageKey:@"button_image" imageKey:nil textKey:@"COURSE_SCHEDULE_BUTTON" textColorKey:@"welcome_screen_buttons_text_color"];
    
    CGFloat verticalOffset = courseScheduleButton.bottom;
    
    if (![NSString isNullOrEmpty:_course.courseUrl]) {
        [Utils customizeButton:courseWebsiteButton withBgImageKey:@"button_image" imageKey:nil textKey:@"COURSE_WEBSITE_BUTTON" textColorKey:@"welcome_screen_buttons_text_color"];
        courseWebsiteButton.hidden = NO;
        courseWebsiteButton.top = verticalOffset + VERTICAL_SPACE;
        verticalOffset = courseWebsiteButton.bottom;
    
    }
    if (![NSString isNullOrEmpty:_course.faculty.facultyUrl]) {
        [Utils customizeButton:facultyWebsiteButton withBgImageKey:@"button_image" imageKey:nil textKey:nil textColorKey:@"welcome_screen_buttons_text_color"];
        [facultyWebsiteButton setTitle:_course.faculty.facultyName forState:UIControlStateNormal];
        facultyWebsiteButton.hidden = NO;
        facultyWebsiteButton.titleLabel.minimumFontSize = FACULTY_BUTTON_MINI_FONT_SIZE;
        facultyWebsiteButton.titleLabel.adjustsFontSizeToFitWidth = YES;
        facultyWebsiteButton.top = verticalOffset + VERTICAL_SPACE;
        verticalOffset = facultyWebsiteButton.bottom;
    }
    
    //if ([[[ConfigurationManager instance] applicationConfigValueForKey:CAN_RECEIVE_NOTIFICATIONS] boolValue])
    if (YES)
    {
        [Utils customizeButton:notificationsButton withBgImageKey:@"button_image" imageKey:nil textKey:@"NOTIFICATIONS_BUTTON_TITLE" textColorKey:@"welcome_screen_buttons_text_color"];
        notificationsButton.hidden = NO;
        notificationsButton.top = verticalOffset + VERTICAL_SPACE;
        verticalOffset = notificationsButton.bottom;
        
    }
    
    // Header text
    headerLabel.hidden = NO;
    headerLabel.text = NSLocalizedString(@"TEACHERS_TABLE_VIEW_HEADER", nil);
    headerLabel.top = verticalOffset + VERTICAL_SPACE;
    verticalOffset = headerLabel.bottom;
    
    // Teachers table
    teachersTableView.top = verticalOffset + VERTICAL_SPACE/2;
    teachersTableView.height = [_course.teachers count] * 43;
    [teachersTableView setHidden:NO];
    [teachersTableView reloadData];
    [teachersTableView setScrollEnabled:NO];
    teachersTableView.layer.cornerRadius = 10;
    
    // Scroll view
    [scrollView setContentSize:CGSizeMake(self.view.width, teachersTableView.bottom + VERTICAL_SPACE)];
}

#pragma mark - UITableView Data Source Methods

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [_course.teachers count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"Cell"];
    }
    Teacher *teacher = [_course.teachers objectAtIndex:indexPath.row];
    cell.textLabel.text = [NSString stringWithFormat:@"%@ %@", teacher.firstName, teacher.lastName];
    cell.detailTextLabel.text = teacher.position;
    return cell;
}

#pragma mark - Table View Delegate Methods

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    // Present the teacher details screen for the selected teacher
    Teacher *teacher = [_course.teachers objectAtIndex:indexPath.row];
    TeacherDetailsViewController *teacherDetails = [[TeacherDetailsViewController alloc] initWithNibName:@"TeacherDetailsViewController" teacher:teacher];
    teacherDetails.title = [NSString stringWithFormat:@"%@ %@", teacher.firstName, teacher.lastName];
    [self.navigationController pushViewController:teacherDetails animated:YES];
    
}

#pragma mark - UI Interaction

- (IBAction)courseScheduleButtonPressed:(id)sender {
    CourseBookingsViewController *courseBookings = [[CourseBookingsViewController alloc] initWithNibName:@"CourseBookingsViewController" course:_course];
    courseBookings.title = courseScheduleButton.titleLabel.text;
    [self.navigationController pushViewController:courseBookings animated:YES];
}


- (IBAction)courseWebSiteButtonPressed:(id)sender {
    [self presentWebBrowserWithUrl:_course.courseUrl title:NSLocalizedString(@"COURSE_WEBSITE_BUTTON", nil)];
}


- (IBAction)facultyWebsiteButtonPressed:(id)sender {
    [self presentWebBrowserWithUrl:_course.faculty.facultyUrl title:_course.faculty.facultyName];
}
- (IBAction)notificationsButtonPressed:(id)sender {
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:NSLocalizedString(@"NOTIFICATIONS_ACTION_SHEET_TITLE", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"ALERT_CANCEL" , nil) destructiveButtonTitle:nil otherButtonTitles:NSLocalizedString(@"NOTIFICATIONS_SUBSCRIBE", nil), NSLocalizedString(@"NOTIFICATIONS_UNSUBSCRIBE", nil), nil];
    [actionSheet showInView:self.view];
}



- (void)presentWebBrowserWithUrl:(NSString *)url title:(NSString *)title{
    WebBrowserViewController *webViewController = [[WebBrowserViewController alloc] initWithNibName:@"WebBrowserViewController" urlString:url];
    webViewController.title = title;
    [self.navigationController pushViewController:webViewController animated:YES];
}

#pragma mark - UIActionSheet Delegate Methods

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        [Utils showLoadingOn:self];
        // Subscribe
        [[NotificationsManager instance] subscribeForNotificationsForCourse:_course delegate:self];
    } else if (buttonIndex == 1) {
        [Utils showLoadingOn:self];
        // Unsubscribe
        [[NotificationsManager instance] unsubscribeForNotificationsForCourse:_course delegate:self];
    }
}

#pragma mark - Courses Protocol Delegate Method

- (void)didReceiveCourseDetailsWithSuccess:(id)object forTicket:(Ticket *)ticket {
    if (!_isOnScreen)
        return;
    [Utils hideLoadingOn:self];
    [self setUpUI];
}

- (void)didReceiveCourseDetailsWithFailure:(id)object forTicket:(Ticket *)ticket {
    if (!_isOnScreen)
        return;
    [Utils hideLoadingOn:self];
    WSError *error = object;
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:error.errorMessage delegate:self cancelButtonTitle:NSLocalizedString(@"ALERT_CANCEL", nil) otherButtonTitles:NSLocalizedString(@"ALERT_RETRY", nil), nil];
    alertView.tag = ALERT_TAG_COURSE_DETAILS;
    alertView.delegate = self;
    [alertView show];
}

#pragma mark - Notifications Protocol

- (void)didSubscribeWithSuccessForTicket:(Ticket *)ticket {
    [Utils hideLoadingOn:self];
    if (!_isOnScreen) {
        return;
    }
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:NSLocalizedString(@"SUBSCRIBE_SUCCESS", nil) delegate:nil cancelButtonTitle:NSLocalizedString(@"ALERT_OK", nil) otherButtonTitles: nil];
    [alertView show];
}

- (void)didSubscribeWithFailure:(id)object forTicket:(Ticket *)ticket {
    [Utils hideLoadingOn:self];
    if (!_isOnScreen) {
        return;
    }
    WSError *error = object;
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:error.errorMessage delegate:self cancelButtonTitle:NSLocalizedString(@"ALERT_CANCEL", nil) otherButtonTitles:NSLocalizedString(@"ALERT_RETRY", nil), nil];
    alertView.delegate = self;
    alertView.tag = ALERT_TAG_SUBSCRIBE;
    [alertView show];
}

- (void)didUnsubscribeWithSuccessForTicket:(Ticket *)ticket {
    [Utils hideLoadingOn:self];
    if (!_isOnScreen) {
        return;
    }
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:NSLocalizedString(@"UNSUBSCRIBE_SUCCESS", nil) delegate:nil cancelButtonTitle:NSLocalizedString(@"ALERT_OK", nil) otherButtonTitles: nil];
    [alertView show];
}

- (void)didUnsubscribeWithFailure:(id)object forTicket:(Ticket *)ticket {
    [Utils hideLoadingOn:self];
    if (!_isOnScreen) {
        return;
    }
    WSError *error = object;
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:error.errorMessage delegate:self cancelButtonTitle:NSLocalizedString(@"ALERT_CANCEL", nil) otherButtonTitles:NSLocalizedString(@"ALERT_RETRY", nil), nil];
    alertView.delegate = self;
    alertView.tag = ALERT_TAG_UNSUBSCRIBE;
    [alertView show];
}

#pragma mark - UIAlertView Delegate Methods

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex != alertView.cancelButtonIndex) {
        if (alertView.tag == ALERT_TAG_COURSE_DETAILS) {
            [self getCourseDetails];
        } else if (alertView.tag == ALERT_TAG_SUBSCRIBE) {
            [Utils showLoadingOn:self];
            // Subscribe
            [[NotificationsManager instance] subscribeForNotificationsForCourse:_course delegate:self];
        } else if (alertView.tag == ALERT_TAG_UNSUBSCRIBE) {
            [Utils showLoadingOn:self];
            // Subscribe
            [[NotificationsManager instance] unsubscribeForNotificationsForCourse:_course delegate:self];
        }
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidUnload {
    [self setCourseScheduleButton:nil];
    [self setCourseWebsiteButton:nil];
    [self setFacultyWebsiteButton:nil];
    [self setTeachersTableView:nil];
    [self setHeaderLabel:nil];
    [self setScrollView:nil];
    [self setNotificationsButton:nil];
    [super viewDidUnload];
}
@end
